package com.xayq.orap.oauth.authorize;

import org.apache.commons.lang.StringUtils;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.xayq.orap.model.ClientDetails;
import com.xayq.orap.oauth.MyOAuthAuthzRequest;
import com.xayq.orap.utils.CommonUtils;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

@Component
public class CodeAuthorizeHandler extends AbstractAuthorizeHandler {


    private static final Logger LOG = LoggerFactory.getLogger(CodeAuthorizeHandler.class);

    
    private OAuthResponse invalidStateResponse() throws OAuthSystemException {
        return OAuthResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                .setError(OAuthError.CodeResponse.INVALID_REQUEST)
                .setErrorDescription("Parameter 'state'  is required")
                .buildJSONMessage();
    }
    @Override
    public OAuthResponse validatePlus() throws OAuthSystemException {
        
    	HttpSession session = oauthRequest.request().getSession();
    	
        //validate state
        final String state = oauthRequest.getState();
        if (StringUtils.isEmpty(state)) {
            LOG.debug("Invalid 'state', it is required, but it is empty");
            return invalidStateResponse();
        }
        if(session.getAttribute("STATE")==null||(!state.equals(session.getAttribute("STATE")+""))){
    		session.setAttribute("STATE", state);
    		session.removeAttribute("SPRING_SECURITY_CONTEXT");
    	}
        
        return null;
    }

    //response code
    @Override
    protected void handleResponse() throws OAuthSystemException, IOException {
        ClientDetails clientDetails = clientDetails();
        String authCode = oAuthService.retrieveAuthCode(clientDetails, getUsername());

        OAuthResponse oAuthResponse = OAuthASResponse
                .authorizationResponse(oauthRequest.request(), HttpServletResponse.SC_OK)
                .location(clientDetails.getRedirectUri())
                .setCode(authCode)
                .buildQueryMessage();
        LOG.debug(" 'code' response: {}", oAuthResponse);

        CommonUtils.writeOAuthQueryResponse(response, oAuthResponse);
    }


}
